package com.tanhua.dubbo.api.impl.mongo;

import com.mongodb.client.result.DeleteResult;
import com.tanhua.domain.db.User;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Long queryEachLoveCount(Long userId) {
        // db.tanhua_users.count({userId:20})
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, Friend.class);
    }

    @Override
    public Long queryLoveCount(Long userId) {
        // db.user_like.count({userId:20})
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    @Override
    public Long queryFanCount(Long userId) {
        // db.user_like.count({likeUserId:20})
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }


    //互相喜欢:   db.tanhua_users.find({userId:20})
    @Override
    public PageResult queryEachLoveList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.limit(pagesize).skip((page - 1) * pagesize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);

        // 统一返回一个map，存储喜欢的用户id、缘分值。再通过List封装map
        List<Map<String, Object>> result = new ArrayList<>();
        // 封装返回结果
        if (friendList != null && friendList.size() > 0) {
            for (Friend friend : friendList) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", friend.getFriendId());
                map.put("score", queryScore(userId, friend.getFriendId()));
                result.add(map);
            }
        }
        // 返回分页对象
        return new PageResult(page, pagesize, (int) count, result);
    }

    //喜欢:      db.user_like.find({userId:20})
    @Override
    public PageResult queryLoveList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.limit(pagesize).skip((page - 1) * pagesize);
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);

        // 统一返回一个map，存储喜欢的用户id、缘分值。再通过List封装map
        List<Map<String, Object>> result = new ArrayList<>();
        // 封装返回结果
        if (userLikeList != null && userLikeList.size() > 0) {
            for (UserLike userLike : userLikeList) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", userLike.getLikeUserId());
                map.put("score", queryScore(userId, userLike.getLikeUserId()));
                result.add(map);
            }
        }
        // 返回分页对象
        return new PageResult(page, pagesize, (int) count, result);
    }


    //谁看过我 :  db.visitors.find({userId:20})
    @Override
    public PageResult queryVisitorList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.limit(pagesize).skip((page - 1) * pagesize);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        long count = mongoTemplate.count(query, Visitors.class);

        // 统一返回一个map，存储喜欢的用户id、缘分值。再通过List封装map
        List<Map<String, Object>> result = new ArrayList<>();
        // 封装返回结果
        if (visitorsList != null && visitorsList.size() > 0) {
            for (Visitors visitors : visitorsList) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", visitors.getVisitorUserId());
                map.put("score", queryScore(userId, visitors.getVisitorUserId()));
                result.add(map);
            }

        }
        // 返回分页对象
        return new PageResult(page, pagesize, (int) count, result);
    }

    @Override
    public void delete(Integer userId, Long likeUserId) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
                        .and("likeUserId").is(likeUserId)
        );
        mongoTemplate.remove(query, UserLike.class);
    }


    // 查询缘分值
    public Long queryScore(Long userId, Long recommendUserId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("recommendUserId").is(recommendUserId)).limit(1);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null) {
            return 70L;
        }
        return recommendUser.getScore().longValue();
    }


    /**
     * 保存喜欢
     */
    @Override
    public String cardsLove(Long userId, Long likeUserId) {
        // 修改tanhua推荐用户表中推荐数据的使用状态
        Query query3 = new Query(Criteria.where("userId").is(userId).and("recommendUserId").in(likeUserId).and("status").is(0))
                .with(Sort.by(Sort.Order.desc("score")));
        Update update = new Update();
        update.set("status", 1);
        mongoTemplate.updateFirst(query3, update, Tanhua_RecommendUser.class);

        // 查询是否是好友,是好友不执行下面操作
        Query query2 = new Query(Criteria.where("userId").is(userId).and("friendId").is(likeUserId));
        if (mongoTemplate.exists(query2, Friend.class)) {
            return null;
        }

        // 查询是否已添加喜欢,已喜欢不执行下面操作
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        if (mongoTemplate.exists(query, UserLike.class)) {
            return null;
        }

        UserLike userLike = new UserLike();
        userLike.setId(ObjectId.get());
        userLike.setUserId(userId);
        userLike.setLikeUserId(likeUserId);
        userLike.setCreated(System.currentTimeMillis());

        mongoTemplate.save(userLike);

        return userLike.getId().toHexString();
    }


    /**
     * 相互喜欢
     */
    @Override
    public boolean isMutualLove(Long userId, Long likeUserId) {
        Criteria criteria1 = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
        Criteria criteria2 = Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId);

        Criteria criteria = new Criteria().orOperator(criteria1, criteria2);

        Query query = new Query(criteria);
        return mongoTemplate.count(query, UserLike.class) == 2;
    }


    /**
     * 删除喜欢
     */
    /**
     * 删除喜欢
     */
    @Override
    public boolean deleteUserLove(Long userId, Long likeUserId) {
        Query query1 = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));

        DeleteResult deleteResult = mongoTemplate.remove(query1, UserLike.class);

        Query query2 = new Query(Criteria.where("recommendUserId").is(likeUserId).and("userId").is(userId));

        Update update = new Update();
        update.set("status", 2);
        mongoTemplate.updateFirst(query2, update, Tanhua_RecommendUser.class);

        return deleteResult.getDeletedCount() == 1;

    }

    @Override
    public Long queryEachLikeCount(Long userId) {
        return mongoTemplate.count(new Query(Criteria.where("userId").is(userId)), Friend.class);
    }


    /**
     * 互相关注：分页查询用户的好友列表
     *
     * @param userId 登陆用户id
     * @return 根据UserLikeVo中数据需要，这里需要返回关注的用户id、缘分值即可。
     */
    @Override
    public PageResult queryEachLikeList(Long userId, Integer page, Integer pageSize) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        ).skip((page - 1) * pageSize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

        // 返回的数据：关注好友的用户id、缘分值
        List<Map<String, Object>> list = new ArrayList<>();
        if (friendList != null) {
            for (Friend friend : friendList) {
                Map<String, Object> map = new HashMap<>();
                map.put("uid", friend.getFriendId());
                map.put("score", queryScore(friend.getUserId(), friend.getFriendId()));
                list.add(map);
            }
        }
        Long count = mongoTemplate.count(query, Friend.class);
        return new PageResult(page, pageSize, count.intValue(), list);
    }

    /**
     * 我关注
     *
     * @param userId 登陆用户id
     * @return 根据UserLikeVo中数据需要，这里需要返回关注的用户id、缘分值即可。
     */
    @Override
    public PageResult queryUserLikeList(Long userId, Integer page, Integer pageSize) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        );
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);

        //返回的数据：关注好友的用户id、缘分值
        List<Map<String, Object>> list = new ArrayList<>();
        if (userLikeList != null) {
            for (UserLike userLike : userLikeList) {
                Map<String, Object> map = new HashMap<>();
                map.put("uid", userLike.getLikeUserId());
                map.put("score", queryScore(userLike.getUserId(), userLike.getLikeUserId()));
                list.add(map);
            }
        }
        Long count = mongoTemplate.count(query, UserLike.class);
        return new PageResult(page, pageSize, count.intValue(), list);
    }

    /**
     * 谁看过我
     *
     * @param userId 登陆用户id
     * @return 根据UserLikeVo中数据需要，这里需要返回访客的用户id、缘分值即可。
     */
    @Override
    public PageResult queryVisitsList(Long userId, Integer page, Integer pageSize) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        );
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);

        // 返回的数据：看过我的用户id、缘分值
        List<Map<String, Object>> list = new ArrayList<>();
        if (visitorsList != null) {
            for (Visitors visitors : visitorsList) {
                Map<String, Object> map = new HashMap<>();
                map.put("uid", visitors.getVisitorUserId());
                map.put("score", queryScore(visitors.getUserId(), visitors.getVisitorUserId()));
                list.add(map);
            }
        }
        Long count = mongoTemplate.count(query, Visitors.class);
        return new PageResult(page, pageSize, count.intValue(), list);
    }

    @Override
    public void save(UserLike userLike) {
        mongoTemplate.save(userLike);
    }

    @Override
    public Boolean isLove(Long userId, Long uid) {
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(uid));
        return mongoTemplate.exists(query, UserLike.class);
    }

    /**
     * 粉丝
     *
     * @param userId 登陆用户id
     * @return 根据UserLikeVo中数据需要，这里需要返回粉丝的用户id、缘分值即可。
     */
    @Override
    public PageResult queryFanList(Long userId, Integer page, Integer pageSize) {
        Query query = new Query(
                Criteria.where("likeUserId").is(userId)
        );
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);

        // 返回的数据：粉丝用户id、粉丝与我的缘分值
        List<Map<String, Object>> list = new ArrayList<>();
        if (userLikeList != null) {
            for (UserLike userLike : userLikeList) {
                Map<String, Object> map = new HashMap<>();
                map.put("uid", userLike.getUserId());
                map.put("score", queryScore(userLike.getLikeUserId(), userLike.getUserId()));
                list.add(map);
            }
        }
        Long count = mongoTemplate.count(query, UserLike.class);
        return new PageResult(page, pageSize, count.intValue(), list);
    }
}
